<template>
	<div class="chat">
		<!-- 顶部导航 -->
		<van-nav-bar
		  title="小智同学"
		  left-text="返回"
		  left-arrow
		  @click-left="$router.back()"
		  class="app-nav-bar"
		  fixed
		/>
		<!-- 消息列表 -->
		<div class="messageList" ref="listbox">
			
			<div 
				class="list-item"
				v-for="(item,index) in msgArr" 
				:key="index">
					<h6>{{item.name}}</h6>
					<p>{{item.msg}}</p>
				</div>
			
		</div>
		
		<!-- 底部发送信息 -->
		<van-cell-group class="sendMessage">
			<van-field
				center
				type="text"
				placeholder='请输入消息'
				maxlength="25"
				clearable
				v-model="message"
			>
				<van-button 
				slot="button"
				size="small"
				type="info"
				@click="socketSend"
				>发送消息</van-button>
			</van-field>
		</van-cell-group>
	</div>
</template>

<script>
	
	import { setItem,getItem } from '@/utils/storage.js'
	export default {
		name:"chat",
		data(){
			return {
				message:'',
				socket:null,
				flag : false,
				msgArr:getItem('chat-messages')||[],
				path:"wss://echo.websocket.org"
			}
		},
		created(){
			this.createWebSocket()
			this.initWebSocket()
		},
		mounted(){
			
			this.scrollTobottom()
			
		},
		methods:{
			createWebSocket(){
				
					this.socket = new WebSocket(this.path)
					this.initWebSocket()
				
				
			},
			initWebSocket(){
				
				this.socket.onopen = this.socketOnopen
				this.socket.onerror = this.socketOnerror
				this.socket.onmessage = this.socketMessage
				this.socket.onclose = this.socketClose
			},
			socketOnopen(){
				this.flag=true
				console.log('链接成功')
			},
			socketOnerror(){
				
				console.log('链接出错,尝试重新链接')
				
				this.reconnect()
			},
			socketMessage(e){
				this.msgArr.push({'name':'小智','msg':e.data})
			},
			socketClose(){
			   console.log('已经离开了活动页')
			},
			socketSend(){
				this.socket.send(this.message)
				this.msgArr.push({'name':'自己','msg':this.message})
				this.message=""
			},
			scrollTobottom(){
				let listbox = this.$refs['listbox']
				this.$nextTick(()=>{
					listbox.scrollTop = listbox.scrollHeight
				})
			},
			reconnect(){
				let that = this
				if(this.flag) return
				this.flag = true
				console.log(that.path)
				setTimeout(function(){
					console.log(that.path)
					
					that.createWebSocket()
					that.flag = false
				},1000)
			}
		},
		destroyed(){
			this.socketClose()
		},
		
		watch:{
			msgArr:function(newValue){
				setItem('chat-messages',newValue)
				this.scrollTobottom()
			}
		}
	}
</script>

<style socped lang="less">
	.chat{
		.messageList{
			position:fixed;
			bottom:44px;
			top:46px;
			left:0;
			right:0;
			overflow-y:auto;
			.list-item{
				padding:5px 0;
				h6,p{
					padding: 0;
					margin: 0;
				}
				p{
					padding:2px 0;
					font-size:14px;
				}
			}
			
		}
		.van-cell{
			height:100%;
			padding:0;
			padding: 0 10px;
		}
		.sendMessage{
			position:fixed;
			bottom:0;
			left:0;
			right:0;
			height:44px;
			line-height: 44px;
		}
	}
</style>
